package com.project.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.config.MsgProperites;
import com.project.entity.qo.MsgTemplateParam;
import com.project.exception.ServiceException;
import com.project.handler.GlobalHandlerException;
import com.project.result.ResultCode;
import com.project.service.MsgService;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author qjj
 * @create 2022/3/26 14:16
 */
@Service
public class MsgServiceImpl extends GlobalHandlerException implements MsgService {
    public static final String PREFIX_REDIS_KEY = "msg:phone:";
    public static final String VERIFICATION_CODE_RETURN_VALUE = "Ok";
    @Resource
    private MsgProperites msgProperites;
    @Resource
    private IAcsClient iAcsClient;
    @Resource
    private ValueOperations<String,Object> valueOperations;
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public String sendMsg(String phone) {
        Object o = valueOperations.get(PREFIX_REDIS_KEY + phone);
        if (!ObjectUtils.isEmpty(o)){
            throw new ServiceException(ResultCode.PERIOD_OF_VALIDITY);
        }
        //1：处理验证码
        String code = RandomUtil.randomNumbers(6);
        //2: 把验证码转换成json格式
        MsgTemplateParam msgTemplateParam = new MsgTemplateParam();
        msgTemplateParam.setCode(code);
        //核心对象
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(msgProperites.getSignName());
        request.setTemplateCode(msgProperites.getTemplateCode());
        try {
            request.setTemplateParam(objectMapper.writeValueAsString(msgTemplateParam));
            SendSmsResponse response = iAcsClient.getAcsResponse(request);
            String message = response.getMessage();
            if (VERIFICATION_CODE_RETURN_VALUE.equals(message)){
                valueOperations.set(PREFIX_REDIS_KEY+phone,code,Duration.ofMinutes(5));
            }
        } catch (JsonProcessingException | ClientException e) {
            throw new ServiceException(ResultCode.ERROR);
        }
        return "success";
    }
}
